import {extname} from 'node:path';
import {existsSync, createReadStream} from 'node:fs';
import ejs from 'ejs';
import mime from 'mime';

import {assetParam} from './paths.mjs';

function serveAsset(res, fsPath) {
  if (!existsSync(fsPath)) {
    res.writeHead(404).end('404 Not Found');
    return;
  }

  try {
    const contentType = mime.getType(extname(fsPath));
    res.setHeader('Content-Type', contentType);

    const fsStream = createReadStream(fsPath);
    fsStream.pipe(res);
  } catch (err) {
    res.writeHead(500).end('500 Internal Error\n' + err);
  }
}

function servePage(req, res, htmlTemplate) {
  const url = new URL(req.url, `http://${req.headers.host}`);
  const reqPath = url.pathname;
  let parentDirCount = 0;
  for (let i = 1; i < reqPath.length; i++) {
    if (reqPath[i] === '/') parentDirCount++;
  }
  const rootRelPath = '../'.repeat(parentDirCount);
  const assetPrefix = rootRelPath + assetParam;

  const data = {assetPrefix};
  const html = ejs.render(htmlTemplate, data);
  res.setHeader('Content-Type', 'text/html; charset=utf-8');
  res.end(html);
}

export {serveAsset, servePage};
